/*
 * @Author: yangzonglong
 * @Date: 2021-03-03 14:44:59
 * @version: v1.0.0
 * @Descripttion: Input 控制器
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 15:36:44
 * @Auditor:
 */
import React, { useState, useEffect } from 'react';
import InputFormItemController from './../components/InputFormItemController';
import useControlOptions from '../../hooks/useControlOptions';
import { InputProps } from './Input';
import useFdStore from '../../hooks/useFdStore';
import { flatControl, uniqueFunc } from './../../util';

const linkType = ['dataLink', 'dataLinkComBox'];
const selectOptions = [{
  value: 'label',
  label: 'label',
}, {
  value: 'value',
  label: 'value',
}];
let dataObj: any = {};




const Controller = () => {
  const {
    state: { list },
  } = useFdStore();

  const { options, changeFormItemProps, changeControlProps } = useControlOptions<InputProps>('inputProps');

  const [componentsArray, setComponentsArray] = useState<any[]>([]);

  useEffect(() => {
    const flatList = flatControl(list);
    let _list = flatList?.filter((item) => linkType.includes(item.type));
    let _select = flatList?.filter((item) => item.type === 'select');


    setComponentsArray(_list?.concat(_select || []).map((item) => ({ label: item?.options?.formItemProps?.label, value: item?.options?.formItemProps?.name })));

    _select?.forEach((element) => {
      dataObj[element?.options?.formItemProps?.name] = selectOptions;
    });

    _list?.forEach((element) => {
      const filedShowName = element?.options?.inputProps?.filedShowName;
      const extraFieldName = element?.options?.inputProps?.extraFieldName || [];
      let bindArr = filedShowName ?
        (typeof filedShowName === 'string' ? [{
          value: filedShowName,
          label: filedShowName,
        }, ...extraFieldName] : (filedShowName?.concat(extraFieldName))) : [];

      bindArr = uniqueFunc(bindArr, 'value');

      dataObj[element?.options?.formItemProps?.name] = bindArr;
    });
  }, [list]);

  return (
    <>
      <InputFormItemController
        placeholder={options.inputProps?.placeholder}
        placeholderEn={options.inputProps?.placeholderEn}
        initialValue={options.inputProps?.initialValue}
        onChangeControlProps={(key: string | any, value?: string) =>
          changeControlProps(
            'inputProps',
            typeof key === 'string' ? { ...options.inputProps, [key]: value } : { ...options.inputProps, ...key },
            true
          )
        }
        onChange={changeFormItemProps}
        options={options?.formItemProps}
        inputProps={options?.inputProps}
        showComponentsArray={componentsArray || []}
        showFiledArray={dataObj?.[options?.inputProps?.bindName!] || []}
      />
    </>
  );
};

export default Controller;
